package org.domain.sigepac.converter;

import java.text.ParseException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.swing.text.MaskFormatter;

/**
 * Conversor para uso com máscaras
 *
 * @author marcelo.guimaraes
 */
public abstract class ConversorMascara implements Converter {

	/**
	 * Retorna o padrão da máscara conforme o componente {@link MaskFormatter}.
	 *
	 * @return padrão da máscara.
	 */
	protected abstract String mascara();

	public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
	  if(value == null) {
      return null;
    } else
      if(value.trim().equals("")) {
        return null;
    }
		try {
			MaskFormatter formatter = new MaskFormatter(mascara());
			formatter.setValueContainsLiteralCharacters(false);
			formatter.setPlaceholderCharacter('_');
			if(formatter.valueToString("").equals(value)) {
			  return null;
			}
			return formatter.stringToValue(value);
		} catch (ParseException e) {
		  e.printStackTrace();
		  return value;
		}
	}

	
	public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
	  if(value == null) {
      return null;
    } else if(value.toString().trim().equals("")) {
      return null;
    }
		try {
			MaskFormatter formatter = new MaskFormatter(mascara());
			formatter.setValueContainsLiteralCharacters(false);
			return formatter.valueToString(value);
		} catch (ParseException e) {
		  e.printStackTrace();
			return value.toString();
		}
	}

}
